﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using AMInstantMessagingServerAPI;
using BaseSimpleAPI;
using AMInstantMessagingDao;
using BaseSimpleDao;

namespace AMInstantMessagingServerAPI
{
    public class UserController : BaseController<UserModel, UserEditModel, UserViewModel>
    {
        public override AuthorizationStatus GetAuthorizationStatus(string action, long requestid, long objectid = 0)
        {
            return AuthorizationStatus.Accept;
        }

        /// <summary>
        /// 我是谁
        /// </summary>
        /// <returns></returns>
        public StatusData WhoAmI()
        {
            long user_id = Request.GetCurrentUserId();
            var user_model = Service.GetItemById(user_id);
            if (user_model == null)
                return StatusData.Error(StatusDataPrompt.GetStatusDataPrompt().NotFindObjects);

            return StatusData<UserModel>.Success(user_model);
        }

        /// <summary>
        /// 根据账户密码登录
        /// </summary>
        /// <param name="UserName"></param>
        /// <param name="Password"></param>
        /// <returns></returns>
        public StatusData Login(LoginModel model, ClientType clienttype)
        {
            model.Password = TokenHelper.MD5Encrypt(model.Password);
            var user_model = Service.GetFirstOrDefault(new List<BaseFilter> { { "UserName", model.UserName }, { "Password", model.Password } });

            if (user_model == null)
                return StatusData.Error(StatusDataPrompt.GetStatusDataPrompt().UserNameOrPasswordError);

            string token = string.Empty;
            while (true)
            {
                token = TokenHelper.GetInstance().GetRandomKey(32);
                if (SimpleCache.GetInstance().GetCacheClientInfoModel(token) == null)
                {
                    SimpleCache.GetInstance().CacheClientInfoModel(token, new UserClientInfo
                    {
                        ClientType = clienttype,
                        LoginTime = DateTime.Now,
                        UserId = user_model.Id,
                    });

                    break;
                }
            }

            return StatusData<string>.Success(token);
        }


    }
}
